<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox, useId } from 'element-plus'

import { 
  GetAllUserApi, 
  createUserApi, 
  updateUserInfoApi,
  deleteUserApi,
  resetPasswordApi
} from '@/api/login'
// props

// 定义变量
// 控制用户列表弹框显隐
const userManageVisible = ref(false)
// 控制修改用户信息弹框显隐
const addVisible = ref(false)
const updateVisible = ref(false)
const resetVisible = ref(false)
const userInfo:any = ref({
  userName: '',
  name: '',
  password: '',
  id: '',
  userGroupId: '',
  userDeptId: ''
})

// 输入框规则
const rules = reactive({
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { required: true, min: 6, max: 20, message: '密码应为6-20位', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入用户名称', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ]
})

// 表格
const tableData:any = ref([])

// 判断是修改还是新增
const operate = ref('add')

const cellStyle = {
  textAlign: 'center'
}

const headStyle = {
  textAlign: 'center'
}

// 定义方法
// 展示弹框
const showUserManage = async () => {
  getUserList()
  userManageVisible.value = true
}

const getUserList = async () => {
  let res = await GetAllUserApi()
  console.log('获取用户列表------>', res)
  if (res.code === -1) {
    ElMessage({
      // message: `${res.message}`,
      message: '网络请求中断获取数据错误！',
      type: 'warning'
    })
    return
  }
  tableData.value = []
  tableData.value = [ ...res.result ]
}

// 取消按钮
const cancellation = () => {
  userInfo.value.name = ''
  userInfo.value.userName = ''
  userInfo.value.password = ''
  addVisible.value = false
  updateVisible.value = false
  resetVisible.value = false
}

// 确认按钮
const confirm = async () => {
  // if ( !userInfo.userName || !userInfo.name || !userInfo.password) {
  //   ElMessage({
  //     message: '用户信息不能为空！！！',
  //     type: 'warning'
  //   })
  //   return
  // }
  let data = {
    userName: userInfo.value.userName,
    name: userInfo.value.name,
    userGroupId: null,
    userDeptId: null, 
    emailAddress: '123@qq.com', 
    surname: '',
    roles: [],
    isActive: true,
    password: userInfo.value.password
  }
  let resetData = {
    userName: userInfo.value.userName,
    newPassword: userInfo.value.password
  }
  console.log('userInfo', userInfo)
  let updatetData = {
    // userName: userInfo.value.userName,
    // name: userInfo.value.name,
    // userGroupId: null,
    // userDeptId: null
    ...userInfo.value
  }
  let res
  if (operate.value === 'add') {
    if ( !userInfo.value.userName || !userInfo.value.name || !userInfo.value.password) {
      ElMessage({
        message: '用户信息不能为空！！！',
        type: 'warning'
      })
      return
    } else if (userInfo.value.password.length < 6 || userInfo.value.password.length > 20) {
      ElMessage({
        message: '密码不能小于6位或者大于20位！！！',
        type: 'warning'
      })
      return
    }
    for (let i = 0; i < tableData.value.length ; i++) {
      if (tableData.value[i].userName === userInfo.value.userName) {
        ElMessage({
          message: '账号已存在，请重新输入！！！',
          type: 'warning'
        })
        userInfo.value.userName = ''
        return
      }
    }
    res = await createUserApi(data)
    if (!res.success) {
      ElMessage({
        message: '添加用户失败！！！',
        type: 'warning'
      })
    } else {
      ElMessage({
        message: '添加用户成功！！！',
        type: 'success'
      })
      getUserList()
    }
  } else if (operate.value === 'reset') {
    console.log('密码长度---->', userInfo.value.password.length)
    if (!userInfo.value.password ) {
      ElMessage({
        message: '新密码不能为空！！！',
        type: 'warning'
      })
      return
    } else if (userInfo.value.password.length < 6 || userInfo.value.password.length > 20) {
      ElMessage({
        message: '密码不能小于6位或者大于20位！！！',
        type: 'warning'
      })
      return
    }
    let resetRes = await resetPasswordApi(resetData)
    console.log('重置密码----->', resetData)
    if (!resetRes.success) {
      ElMessage({
        message: '重置失败！！！',
        type: 'warning'
      })
    } else {
      ElMessage({
        message: '重置成功！！！',
        type: 'success'
      })
      getUserList()
    }
  } else {
    if (!userInfo.value.name) {
      ElMessage({
        message: '新用户名称不能为空！！！',
        type: 'warning'
      })
      return
    }
    let res = await updateUserInfoApi(updatetData)
    console.log('修改名称----->', resetData)
    if (!res.success) {
      ElMessage({
        message: '修改失败！！！',
        type: 'warning'
      })
    } else {
      ElMessage({
        message: '修改成功！！！',
        type: 'success'
      })
      getUserList()
    }
  }
  userInfo.value.name = ''
  userInfo.value.userName = ''
  userInfo.value.password = ''
  userInfo.value.id = ''
  userInfo.value.userGroupId = ''
  userInfo.value.userDeptId = ''
  addVisible.value = false
  updateVisible.value = false
  resetVisible.value = false
}

// 修改用户信息
const updateUserInfo = (row:any) => {
  operate.value = 'update'
  // userInfo.value.name = row.name
  // userInfo.value.userName = row.userName
  // userInfo.value.id = row.id
  // userInfo.value.userGroupId = row.userGroupId
  // userInfo.value.userDeptId = row.userDeptId
  userInfo.value = { ...row }
  console.log('修改用户信息---------->', userInfo)
  updateVisible.value = true
}

// 重置密码
const resetUserPassword = (row: any) => {
  operate.value = 'reset'
  userInfo.value.name = row.name
  userInfo.value.userName = row.userName
  userInfo.value.id = row.id
  userInfo.value.userGroupId = row.userGroupId
  userInfo.value.userDeptId = row.userDeptId
  console.log('修改用户信息---------->', userInfo)
  resetVisible.value = true
}

// 添加用户
const addUser = () => {
  operate.value = 'add'
  addVisible.value = true
}

// 删除用户
const deleteUser = (row:any) => {
  console.log('删除的用户----------->', row)
  ElMessageBox.alert('是否删除？', '确认', {
    confirmButtonText: '确认',
    callback: async () => {
      let data = {
        id: row.id
      }
      let res = await deleteUserApi(data)
      console.log('删除----->', res)
      if (res.code === -1) {
        ElMessage({
          type: 'info',
          message: '删除失败！'
        })
      } else {
        ElMessage({
          type: 'success',
          message: '删除成功！'
        })
        getUserList()
      }
    }
  })
}

defineExpose({
  showUserManage
})
</script>

<template>
  <el-dialog
    v-model="userManageVisible"
    class="user-manage-dialog"
  >
    <template #header>
      <div class="user-manage-header-box">
        <div class="title">
          用户列表
        </div>
        <div
          class="add-user-btn"
          @click="addUser"
        >
          添加用户
        </div>
      </div>
    </template>
    <div class="user-table-box">
      <el-table
        :border="true"
        :cell-style="cellStyle"
        :header-cell-style="headStyle"
        :data="tableData"
        max-height="370"
        size="mini"
      >
        <el-table-column
          prop="name"
          label="用户名称"
        />
        <el-table-column
          prop="userName"
          label="账号"
        />
    
        <el-table-column
          width="300px"
          label="操作"
        >
          <template #default="scope">
            <div class="btn-box">
              <div
                class="update-btn"
                @click="updateUserInfo(scope.row)"
              >
                修改名称
              </div>
              <div
                class="reset-btn"
                @click="resetUserPassword(scope.row)"
              >
                重置密码
              </div>
              <div
                class="delete-btn"
                @click="deleteUser(scope.row)"
              >
                删除
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      v-model="updateVisible"
      width="30%"
      :title="operate === 'add' ? '添加用户' : operate === 'update' ? '修改用户信息' : '重置用户密码'"
      append-to-body
      @close="cancellation"
    >
      <el-form
        label-position="right"
        label-width="80px"
        :model="userInfo"
        :rules="rules"
      >
        <el-form-item
          label="用户名称"
          prop="name"
        >
          <el-input
            v-model="userInfo.name"
            :disabled="operate === 'add' ? false : operate === 'update' ? false : true "
          />
        </el-form-item>
        <el-form-item
          label="账号"
          prop="userName"
        >
          <el-input
            v-model="userInfo.userName"
            :disabled="operate === 'add' ? false : true"
          />
        </el-form-item>
        <el-form-item
          v-show="operate !== 'update'"
          label="密码"
          prop="password"
        >
          <el-input
            v-model="userInfo.password"
            type="password"
          />
        </el-form-item>
        <div class="update-btn-box">
          <div
            class="cancellation-btn"
            @click="cancellation"
          />
          <div
            class="confirm-btn"
            @click="confirm"
          />
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      v-model="addVisible"
      width="30%"
      :title="operate === 'add' ? '添加用户' : operate === 'update' ? '修改用户信息' : '重置用户密码'"
      append-to-body
      @close="cancellation"
    >
      <el-form
        label-position="right"
        label-width="80px"
        :model="userInfo"
        :rules="rules"
      >
        <el-form-item
          label="用户名称"
          prop="name"
        >
          <el-input
            v-model="userInfo.name"
            :disabled="operate === 'add' ? false : operate === 'update' ? false : true"
          />
        </el-form-item>
        <el-form-item
          label="账号"
          prop="userName"
        >
          <el-input
            v-model="userInfo.userName"
            :disabled="operate === 'add' ? false : true"
          />
        </el-form-item>
        <el-form-item
          v-show="operate !== 'update'"
          label="密码"
          prop="password"
        >
          <el-input
            v-model="userInfo.password"
            type="password"
          />
        </el-form-item>
        <div class="update-btn-box">
          <div
            class="cancellation-btn"
            @click="cancellation"
          />
          <div
            class="confirm-btn"
            @click="confirm"
          />
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      v-model="resetVisible"
      width="30%"
      :title="operate === 'add' ? '添加用户' : operate === 'update' ? '修改用户信息' : '重置用户密码'"
      append-to-body
      @close="cancellation"
    >
      <el-form
        label-position="right"
        label-width="80px"
        :model="userInfo"
        :rules="rules"
      >
        <el-form-item
          label="用户名称"
          prop="name"
        >
          <el-input
            v-model="userInfo.name"
            :disabled="operate === 'add' ? false : operate === 'update' ? false : true"
          />
        </el-form-item>
        <el-form-item
          label="账号"
          prop="userName"
        >
          <el-input
            v-model="userInfo.userName"
            :disabled="operate === 'add' ? false : true"
          />
        </el-form-item>
        <el-form-item
          v-show="operate !== 'update'"
          label="密码"
          prop="password"
        >
          <el-input
            v-model="userInfo.password"
            type="password"
          />
        </el-form-item>
        <div class="update-btn-box">
          <div
            class="cancellation-btn"
            @click="cancellation"
          />
          <div
            class="confirm-btn"
            @click="confirm"
          />
        </div>
      </el-form>
    </el-dialog>
  </el-dialog>
</template>

<style lang="scss" scoped>
.user-table-box {
  display: flex;
  justify-content: center;
  width: 740px;
  height: 380px;
  background: #fff;
  border-radius: 2px;
  opacity: 1;
  .btn-box {
  align-items: center;
  justify-content: space-around;
  margin-top: 0;
  >div {
    width: 56px;
    height: 28px;
    color: #fff;
    font-size: 14px;
    border-radius: 3px;

    /* background-color: red; */
    &:hover {
      cursor: pointer;
    }
  }
  .update-btn {
    width: 80px;
    background-color: #3ce63c;
  }
  .reset-btn {
    width: 80px;
    background-color: #e6a23c;
  }
  .delete-btn {
    margin-left: 10px;
    background-color: #f56c6c;
  }
}
}
.update-btn-box {
    display: flex;
    flex-direction: row;
    margin-top: 20px;

    /* border: 1px solid red; */
    .confirm-btn {
      width: 120px;
      height: 42px;
      margin-left: 40px;
      background-image: url("../assets/bckImg/confirm.png");

      /* border: 1px solid red; */
    }
    .confirm-btn:hover {
      cursor: pointer;
    }
    .confirm-btn:active {
      background: rgba($color: #2191ffff, $alpha: 90%);
      cursor: pointer;
    }
    .cancellation-btn {
      width: 120px;
      height: 42px;
      margin-left: 150px;
      background-image: url("../assets/bckImg/cancellation.png");

      /* border: 1px solid red; */
    }
    .cancellation-btn:hover {
      cursor: pointer;
    }
    .cancellation-btn:active {
      background: rgba($color: #a9aeb8ff, $alpha: 90%);
      cursor: pointer;
    }
  }
</style>
<style lang="scss">
.user-manage-dialog {
  width: 800px;
  height: 488px;
  .user-manage-header-box {
    display: flex;
    justify-content: space-between;
    padding-right: 30px;
    .title {
      width: 120px;
      height: 28px;
      color: #4e5969;
      font-weight: 600;
      font-size: 20px;
      font-family: PingFang, sans-serif;
      line-height: 23px;
      background-clip: text;
    }
    .add-user-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100px;
      height: 28px;
      color: #fff;
      font-size: 14px;
      background-color: rgba($color: #2191ffff, $alpha: 90%);
      border-radius: 4px;
      &:hover {
        background-color: rgba($color: #2191ffff, $alpha: 70%);
        cursor: pointer;
      }

      /* border: 1px solid red; */
    }
  }
  .btn-box {
    display: flex;
    flex-direction: row;
    margin-top: 30px;

    /* border: 1px solid red; */
    .confirm-btn {
      width: 120px;
      height: 42px;
      margin-left: 40px;
      background-image: url("../assets/bckImg/confirm.png");

      /* border: 1px solid red; */
    }
    .confirm-btn:hover {
      cursor: pointer;
    }
    .confirm-btn:active {
      background: rgba($color: #2191ffff, $alpha: 90%);
      cursor: pointer;
    }
    .cancellation-btn {
      width: 120px;
      height: 42px;
      margin-left: 250px;
      background-image: url("../assets/bckImg/cancellation.png");

      /* border: 1px solid red; */
    }
    .cancellation-btn:hover {
      cursor: pointer;
    }
    .cancellation-btn:active {
      background: rgba($color: #a9aeb8ff, $alpha: 90%);
      cursor: pointer;
    }
  }
}
</style>